<?php

namespace modules\point\controller;

use modules\order\lib\OrderCreator;
use OpenApi\Attributes as OA;

#[OA\Tag(name: '积分订单', description: '积分订单管理接口')]

class ApiOrderController extends \core\ApiController
{
    protected $sys_tag = 'admin';
    protected $type = 'point';

    protected $model = [
        'order' => '\modules\order\model\OrderModel',
        'order_item' => '\modules\order\model\OrderItemModel',
    ];


    /**
     * 创建订单
     */
    #[OA\Post(
        path: '/point/api-order/create',
        summary: '创建订单',
        tags: ['积分订单'],
        parameters: [
            new OA\Parameter(name: 'items', description: '商品列表', in: 'query', required: true, schema: new OA\Schema(type: 'array')),
            new OA\Parameter(name: 'seller_id', description: '商家ID', in: 'query', schema: new OA\Schema(type: 'integer')),
            new OA\Parameter(name: 'store_id', description: '店铺ID', in: 'query', schema: new OA\Schema(type: 'integer')),
            new OA\Parameter(name: 'address_id', description: '地址ID', in: 'query', schema: new OA\Schema(type: 'integer')),
            new OA\Parameter(name: 'address', description: '收货地址', in: 'query', schema: new OA\Schema(type: 'string')),
            new OA\Parameter(name: 'phone', description: '收货电话', in: 'query', schema: new OA\Schema(type: 'string')),
            new OA\Parameter(name: 'name', description: '收货人姓名', in: 'query', schema: new OA\Schema(type: 'string')),
            new OA\Parameter(name: 'desc', description: '订单备注', in: 'query', schema: new OA\Schema(type: 'string')),
        ],
    )]
    public function actionCreate()
    {
        $flag = false;
        db_action(function () use (&$flag) {
            $user_id = $this->uid;
            $items = $this->post_data['items'] ?? [];
            $orderData = [
                'user_id' => $user_id,
                'type' => 'point',
                'seller_id' => $this->post_data['seller_id'] ?? null,
                'store_id' => $this->post_data['store_id'] ?? null,
                'payment_method' => $this->post_data['payment_method'] ?: 'weixin',
                'address_id' => $this->post_data['address_id'] ?? null,
                'address' => $this->post_data['address'] ?? '',
                'phone' => $this->post_data['phone'] ?? '',
                'name' => $this->post_data['name'] ?? '',
                'desc' => $this->post_data['desc'] ?? '',
                'status' => $this->post_data['status'] ?: 'wait',
                'items' => $items,
                'sys_tag' => $this->sys_tag,
            ];
            $items = $orderData['items'];
            $item = $items[0];
            $product_id = $item['product_id'];
            $where = [
                'id' => $product_id,
                'sys_tag' => 'point',
                //加入排他锁，防止并发问题
                'FOR UPDATE' => TRUE,
            ];
            $product = db_get_one("product", "*", $where);
            if (!$product) {
                return json_error(['msg' => lang('商品不存在')]);
            }
            $orderData['items'][0]['title'] = $product['title'];
            $orderData['items'][0]['num'] = 1;

            if ($product['stock'] <= 0) {
                return json_error(['msg' => lang('商品库存不足')]);
            }
            $point = $product['point'];
            if ($point <= 0) {
                return json_error(['msg' => lang('商品积分设置有误')]);
            }
            $product_type = $product['product_type'];
            if ($product_type == 'point_1') {
                if (!$orderData['name'] || !$orderData['phone'] || !$orderData['address']) {
                    return json_error(['msg' => lang('请填写收货人姓名、电话、地址')]);
                }
            }
            $orderCreator = new OrderCreator();
            $orderCreator->check = false;
            $result = $orderCreator->create($orderData);
            $order_id = $result['id'];
            $order_num = $result['order_num'];
            $point = $product['point'];
            $product_id = $product['id'];
            //更新point字段
            db_update("order", ['point' => $point, 'amount' => 0,'status'=>'paid'], ['id' => $order_id]);
            //更新order_item
            db_update("order_item", ['point' => $point, 'amount' => 0,'status'=>'paid'], ['order_id' => $order_id]);
            //更新商品库存
            db_update("product", ['stock' => $product['stock'] - 1], ['id' => $product_id]);
            //更新user_point
            add_point($user_id, 0 - $point, $type = 'order', $title = '兑换订单号：' . $order_num, $order_num);
            $flag = true;
        });

        if ($flag) {
            return json_success([
                'msg' => lang('订单创建成功')
            ]);
        } else {
            return json_error(['msg' => $result['msg'] ?? lang('订单创建失败')]);
        }
    }
}
